﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

using DreamCube.Foundation.Basic.Utility;
using DreamCube.Framework.Utilities.Office;
using DreamCube.WinForm.Common;

namespace ChangeDFM.UI
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择Excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        /// <summary>
        /// 确定转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(textBox1.Text))
                {
                    MessageBox.Show(this, "请先选中Excel文件！", "提醒");
                    return;
                }

                if (!checkBox1.Checked && !checkBox2.Checked)
                {
                    MessageBox.Show(this, "请选择您要进行何种转换！", "提醒");
                    return;
                }

                if (!File.Exists(textBox1.Text))
                {
                    MessageBox.Show(this, "指定的Excel文件不存在，请确认！", "提醒");
                    return;
                }

                if (MyIO.IsFileUsing(textBox1.Text))
                {
                    MessageBox.Show(this, "指定的Excel文件已经打开了，请先关闭再执行转换！", "提醒");
                    return;
                }
                Thread t = new Thread(new ParameterizedThreadStart((o) =>
                {
                    DoConvert(o.ToString());
                }));
                t.Start(textBox1.Text);
                //ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
                //{
                //    DoConvert(o.ToString());
                //}), textBox1.Text);
                MyWaitingForm.Show(this, "正在转换，请等候");
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                MessageBox.Show(this, "转化过程发生异常！", "提醒");
            }
        }

        /// <summary>
        /// 执行转换的操作
        /// </summary>
        private void DoConvert(String excelFilePath)
        {
            MyExcel excel = null;
            try
            {
                excel = new MyExcel(excelFilePath, false);
                Int32 rowCount = excel.DataRowCount;
                List<String> wrongIndex = new List<String>();
                for (Int32 i = 1; i <= rowCount; i++)
                {
                    //这个是度分秒转换成度的方法
                    if (checkBox1.Checked)
                    {
                        try
                        {
                            String value = MyObject.ToStringEx(excel.GetCellValue(i, (Int32)numericUpDown2.Value), "").Trim();
                            if (String.IsNullOrEmpty(value)) continue;
                            excel.SetCellValue(i, (Int32)numericUpDown1.Value, ConvertToDu(value));
                        }
                        catch (Exception ex)
                        {
                            wrongIndex.Add(i.ToString());
                            MyLog.MakeLog(String.Format("在转换第{0}行数据的时候发生异常：{1}", i, ex.Message), MyLog.LogType.Exception);
                        }
                    }

                    if (checkBox2.Checked)
                    {
                        try
                        {
                            String value = MyObject.ToStringEx(excel.GetCellValue(i, (Int32)numericUpDown4.Value), "").Trim();
                            if (String.IsNullOrEmpty(value)) continue;
                            excel.SetCellValue(i, (Int32)numericUpDown3.Value, ConvertToFenMiao(value));
                        }
                        catch (Exception ex)
                        {
                            wrongIndex.Add(i.ToString());
                            MyLog.MakeLog(String.Format("在转换第{0}行数据的时候发生异常：{1}", i, ex.Message), MyLog.LogType.Exception);
                        }
                    }
                }

                excel.Save();
                excel.Dispose();
                if (wrongIndex.Count == 0)
                {
                    MessageBox.Show(this, "转化成功！", "提醒");
                }
                else
                {
                    String wrongText = String.Format("转换的过程中，有以下这些行的数据转换失败：\r\n{0}", MyEnumerable.JoinEx(wrongIndex, "；"));
                    MessageBox.Show(this, wrongText, "提醒");
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                MessageBox.Show(this, "转化过程发生异常！", "提醒");
            }
            finally
            {
                MyWaitingForm.Hide();
                try
                {
                    if (excel != null)
                    {
                        excel.Save();
                        excel.Dispose();
                    }
                }
                catch (Exception)
                { }
            }
        }

        /// <summary>
        /// 把度显示成度分秒
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static String ConvertToFenMiao(String value)
        {
            if (String.IsNullOrEmpty(value)) return "";
            if(value.EndsWith("°"))value = value.Substring(0,value.Length - 1);
            Double input = Double.Parse(value);
            //获取小数部分
            Double duPart = MyNumber.TruncateEx(input);
            //获取整数部分
            Double du = Math.Truncate(input);

            Double newValue = duPart * 60;
            //相乘之和，整数部分就是分；小数部分再乘以60，然后取余数
            Double fen = Math.Truncate(newValue);
            Double miaoPart = MyNumber.TruncateEx(newValue);
            Double miao = Math.Round(miaoPart * 60, 4);

            return String.Format("{0}°{1}′{2}″", du, fen, miao);
        }

        /// <summary>
        /// 把度分秒转换成度显示的方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static String ConvertToDu(String value)
        {
            if (String.IsNullOrEmpty(value)) return "";
            String du = MyString.Left(value, "°");
            String fen = MyString.Left(MyString.Right(value, "°"), "′");
            String miao = MyString.Right(value, "′");
            if (miao.EndsWith("″")) miao = miao = miao.Substring(0, miao.Length - 1);

            Double fenTodu = MyString.ToDouble(fen) / 60.0;
            Double miaoTodu = MyString.ToDouble(miao) / 3600.0;
            Double result = Math.Round(fenTodu + miaoTodu, 8);
            //String.Format("{0:N8}", result);
            return String.Format("{0}.{1}", du, MyString.Right(result.ToString(), "."));
        }
    }
}
